package com.atlin.project.controller;


import cn.hutool.core.io.FileUtil;
import com.atlin.beaconsapicommon.model.domain.SysUser;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.manager.RedisLimiterManager;
import com.atlin.project.model.dto.file.PreviewFileRequest;
import com.atlin.project.model.dto.file.UploadFileRequest;
import com.atlin.project.model.enums.FileUploadBizEnum;
import com.atlin.project.service.SysUserService;
import com.atlin.project.utils.file.FileUtils;
import com.atlin.project.utils.file.LocalFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 文件接口
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private RedisLimiterManager redisLimiterManager;


    /**
     * 文件上传
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile,
                                           UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        validFile(multipartFile, fileUploadBizEnum);
        SysUser loginUser = sysUserService.getLoginUser(request);
        // 文件目录：根据业务、用户来划分
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%s", fileUploadBizEnum.getValue(), loginUser.getId(), filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
//            cosManager.putObject(filepath, file);
            String fileFinalPath = LocalFileUtil.save(file, filename, FileUtils.getUploadPath(fileUploadBizEnum));
            // 返回可访问地址
            return ResultUtils.success(fileFinalPath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 文件预览下载通用接口
     *
     * @param request
     * @param response
     */
    @PostMapping("/previewFile")
    public void previewFile(@RequestBody PreviewFileRequest previewFileRequest, HttpServletRequest request, HttpServletResponse response) {
        ThrowUtils.throwIf(previewFileRequest == null, ErrorCode.PARAMS_ERROR);
        String filePath = previewFileRequest.getFilePath();
        ThrowUtils.throwIf(StringUtils.isBlank(filePath), ErrorCode.PARAMS_ERROR);

        // TODO 权限校验
        SysUser loginUser = sysUserService.getLoginUser(request);

        LocalFileUtil.previewFile(filePath, response);
    }

    @GetMapping("/previewImage")
    public void previewImage(String imagePath, HttpServletRequest request, HttpServletResponse response) {
        ThrowUtils.throwIf(StringUtils.isBlank(imagePath), ErrorCode.PARAMS_ERROR);

        // TODO 权限校验 文件类型校验 只支持图片类型文件
        SysUser loginUser = sysUserService.getLoginUser(request);

        String suffix = FileUtil.getSuffix(imagePath);
        final List<String> accSuffix = Arrays.asList("jpg", "png", "jpeg", "gif");
        ThrowUtils.throwIf(!accSuffix.contains(suffix), ErrorCode.NO_AUTH_ERROR);

        // 限流 
//        redisLimiterManager.doRateLimiter("previewImage_" + loginUser.getId());

        // 设置缓存控制头
        long TEN_HOUR = 60 * 60 * 10L;
        response.setHeader("Cache-Control", "public, max-age=" + TEN_HOUR);

        LocalFileUtil.previewFile(imagePath, response);
    }

    // /atlin/upload/20241209/PEzJ4hCg-3323567.png
    @GetMapping("/previewImage/{domain}/{bucketName}/{time}/{fileName}")
    public void preview(@PathVariable String domain,
                        @PathVariable String bucketName,
                        @PathVariable String time,
                        @PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) {
        ThrowUtils.throwIf(StringUtils.isAnyBlank(domain, bucketName, time, fileName), ErrorCode.NULL_ERROR);

        String suffix = FileUtil.getSuffix(fileName);
        final List<String> accSuffix = Arrays.asList("jpg", "png", "jpeg", "gif");
        ThrowUtils.throwIf(!accSuffix.contains(suffix), ErrorCode.NO_AUTH_ERROR);

        // 限流 
//        redisLimiterManager.doRateLimiter("previewImage_" + loginUser.getId());

        // 设置缓存控制头
        long TEN_HOUR = 60 * 60 * 10L;
        response.setHeader("Cache-Control", "public, max-age=" + TEN_HOUR);
        String imagePath = "/projectFile/" + domain + '/' + bucketName + '/' + time + '/' + fileName;

        LocalFileUtil.previewFile(imagePath, response);
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_MB = 1024 * 1024L;
        final long FIVE_MB = ONE_MB * 5;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_MB) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        } else if (FileUploadBizEnum.USER_IMPORT.equals(fileUploadBizEnum)) {
            if (fileSize > FIVE_MB) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 5M");
            }
        }
    }
}
